import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/services_eventbus.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:flutter_yres/tool/BlankToolBarTool.dart';
import 'package:flutter_yres/pages/event/LoginEvent.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fake_wechat/fake_wechat.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import '../../tool/AppSaveInfoUtil.dart';
import '../../tool/LoadingUtil.dart';
import 'BindWx.dart';
import '../event/UserInfoEvent.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool isLogin = false, isWxInstall = false, showPhone = true;
  Wechat _wechat = Wechat()
    ..registerApp(
      appId: WX_APPID,
      universalLink: WECHAT_UNIVERSAL_LINK,
    );
  StreamSubscription<WechatAuthResp> _auth;
  WechatAuthResp _authResp;

  final _userNameController = TextEditingController(); //用户名
  final _userPwdController = TextEditingController(); //密码
  // // 响应空白处的焦点的Node
  // FocusNode blankNode = FocusNode();
  // 响应空白处的焦点的Node
  BlankToolBarModel barModel = BlankToolBarModel();
  ScrollController scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    double kWindowstateHeight =
        MediaQueryData.fromWindow(window).padding.top; //状态栏
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Scaffold(
        // appBar: AppBar(
        //     title:Text('登录'),
        //   ),
        resizeToAvoidBottomPadding: true,
        body: BlankToolBarTool.blankToolBarWidget(context,
            model: barModel,
            body: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("images/bg_login.png"),
                    fit: BoxFit.cover,
                  ),
                ),
                margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                // height: kScreenHeight,
                child: SingleChildScrollView(
                    controller: scrollController,
                    child: Column(
                      children: <Widget>[
                        Container(
                            margin:
                                EdgeInsets.only(top: kWindowstateHeight * 3),
                            width: ScreenUtil.getInstance().setWidth(120),
                            height: ScreenUtil.getInstance().setWidth(120),
                            child: Image.asset('images/logo.png')),
                        Container(
                          margin: EdgeInsets.only(
                              top: ScreenUtil.getInstance().setWidth(28)),
                          child: Text(
                            '欢迎登录油然而省',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil.getInstance().setSp(30),
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setWidth(28),
                              ScreenUtil.getInstance().setWidth(28),
                              ScreenUtil.getInstance().setWidth(28),
                              ScreenUtil.getInstance().setWidth(28)),
                          // child: Card(
                          //   elevation: kMargin10,
                          color: Colors.white,
                          child: Column(
                            children: <Widget>[
                              createInputText(_userNameController,
                                  hint: '请输入请输手机号',
                                  imgPath: 'images/icon_iphone.png',
                                  obscureText: false,
                                  type: TextInputType.phone),
                              createInputText(_userPwdController,
                                  hint: '请输入密码',
                                  imgPath: 'images/icon_lock.png',
                                  obscureText: true,
                                  type: TextInputType.visiblePassword),
                              new Container(
                                  margin: EdgeInsets.fromLTRB(
                                      0.0,
                                      ScreenUtil.getInstance().setWidth(20) * 2,
                                      0,
                                      0.0),
                                  width:
                                      ScreenUtil.getInstance().setWidth(750) *
                                          0.8,
                                  child: new RaisedButton(
                                      color: Colors.blue,
                                      shape: StadiumBorder(),
                                      child: new Padding(
                                        padding: new EdgeInsets.all(10.0),
                                        child: new Text(
                                          '登录',
                                          style: new TextStyle(
                                              color: Colors.white,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(NORMAL_FONT_SIZE)),
                                        ),
                                      ),
                                      onPressed: () {
                                        requestLogin();
                                      })),
                                      !isWxInstall?new Container():
                              new Container(
                                  margin: EdgeInsets.fromLTRB(
                                      0.0,
                                      ScreenUtil.getInstance().setWidth(20) * 2,
                                      0,
                                      0.0),
                                  width:
                                      ScreenUtil.getInstance().setWidth(750) *
                                          0.8,
                                  child: new RaisedButton(
                                      color: Colors.green,
                                      shape: StadiumBorder(),
                                      child: new Padding(
                                        padding: new EdgeInsets.all(10.0),
                                        child: new Text(
                                          '微信登录',
                                          style: new TextStyle(
                                              color: Colors.white,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(NORMAL_FONT_SIZE)),
                                        ),
                                      ),
                                      onPressed: () {
                                        if (!isWxInstall) {
                                          Toast.toast(context,
                                              msg: "请先安装微信客户端");
                                          return;
                                        }
                                        // print('object');
                                        _wechat.auth(
                                          scope: <String>[
                                            WechatScope.SNSAPI_USERINFO
                                          ],
                                          state: 'auth',
                                        );
                                      })),
                              new Container(
                                margin: EdgeInsets.fromLTRB(
                                    0.0,
                                    ScreenUtil.getInstance().setWidth(20) * 2,
                                    0,
                                    0.0),
                                child: new Row(
                                  children: <Widget>[
                                    new Expanded(
                                      flex: 1,
                                      child: new FlatButton(
                                          color: Colors.white,
                                          child: new Text(
                                            '注册',
                                            style: new TextStyle(
                                                color: Colors.grey,
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(
                                                            SMALL_FONT_SIZE)),
                                          ),
                                          onPressed: () {
                                            Navigator.of(context)
                                                .pushNamed("register");
                                          }),
                                    ),
                                    new Expanded(
                                      flex: 1,
                                      child: Container(),
                                    ),
                                    new Expanded(
                                      flex: 1,
                                      child: new FlatButton(
                                          color: Colors.white,
                                          child: new Text(
                                            '忘记密码？',
                                            style: new TextStyle(
                                                color: Colors.grey,
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(
                                                            SMALL_FONT_SIZE)),
                                          ),
                                          onPressed: () {
                                            Navigator.of(context)
                                                .pushNamed("forget");
                                          }),
                                    )
                                  ],
                                ),
                              )
                            ],
                          ),
                          // )
                        ),
                      ],
                    )))));
  }

//图标 + 输入框
  Widget createInputText(TextEditingController controller,
      {obscureText: false, String hint, String imgPath, TextInputType type}) {
    return Padding(
        padding: new EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(20) * 2,
            ScreenUtil.getInstance().setWidth(20) * 2,
            ScreenUtil.getInstance().setWidth(20) * 2,
            0),
        child: new Stack(
          alignment: new Alignment(1.0, 1.0),
          //statck
          children: <Widget>[
            new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0),
                    child: new Image.asset(
                      imgPath,
                      fit: BoxFit.fill,
                    ),
                  ),
                  new Expanded(
                    child: new TextField(
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                        // focusNode: _contentFocusNode,
                        controller: controller,
                        keyboardType: type,
                        decoration: new InputDecoration(
                          border: InputBorder.none,
                          hintText: hint,
                        ),
                        obscureText: obscureText),
                  ),
                ]),
            new IconButton(
              icon: new Icon(Icons.clear, color: Colors.black45),
              onPressed: () {
                controller.clear();
              },
            ),
            Divider(
              height: 1,
            ),
          ],
        ));
  }

// 保存账号密码
  void _saveLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString("name", _userNameController.text);
    preferences.setString("pwd", _userPwdController.text);
  }

  void _saveUserMsg(token, uid, group_id) async {
    //存储用户信息
    // SharedPreferences preferences = await SharedPreferences.getInstance();
    saveString('token', token);
    saveString("uid", uid);
    saveString("group_id", group_id);
  }

  // 读取账号密码，并将值直接赋给账号框和密码框
  void _getLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    _userNameController.text = preferences.get("name");
    _userPwdController.text = preferences.get("pwd");
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    barModel.outSideCallback = focusNodeChange;
    _getLoginMsg();
    checkWx();
    _auth = _wechat.authResp().listen(_listenAuth);
  }

  checkWx() async {
    // Map map = new Map();
    // map['sign_type'] = SignType.CHECK_VERSION;
    // Response<String> response =
    //     await HttpUtil().post(Api.VERSION_CHECK, data: getSign(map));
    // Map userMap = json.decode(response.data);
    // if (userMap['code'] == 1 && mounted) {
    isWxInstall = await _wechat.isWechatInstalled();
    setState(() {});
    // }
  }

  void _listenAuth(WechatAuthResp resp) {
    _authResp = resp;
    if (_authResp != null &&
        _authResp.errorCode == WechatSdkResp.ERRORCODE_SUCCESS) {
      _wechat
          .getAccessTokenUnionID(
        appId: WX_APPID,
        appSecret: WX_APP_SECRET,
        code: _authResp.code,
      )
          .then((WechatAccessTokenResp accessTokenResp) {
        if (accessTokenResp.errcode == WechatApiResp.ERRORCODE_SUCCESS) {
          _wechat
              .getUserInfoUnionID(
            openId: accessTokenResp.openid,
            accessToken: accessTokenResp.accessToken,
          )
              .then((WechatUserInfoResp userInfoResp) {
            if (userInfoResp.errcode == WechatApiResp.ERRORCODE_SUCCESS) {
              showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (_) {
                    return new NetLoadingDialog(
                      loadingText: "检测中...",
                      bgColor: Color.fromARGB(255, 0, 0, 0),
                      requestCallBack: null,
                      outsideDismiss: false,
                    );
                  });
              checkIsWxBind(userInfoResp);
              // _showTips(
              //     '用户信息', '${userInfoResp.nickname} - ${userInfoResp.sex}');
            }
          });
        }
      });
    } else {
      Toast.toast(context, msg: "微信登录失败");
    }
  }

  checkIsWxBind(WechatUserInfoResp resp) async {
    Map map = new Map();
    map['openid'] = resp.openid;
    map['type'] = "wx";
    // map['sign_type'] = SignType.CHECK_WX_IS_BIND;
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.CheckRegisterOauthUrl, data: fromData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    if (msg == '成功，已授权' && mounted) {
      saveString(TOKEN, userMap['data']['token']);
      saveString(UID, userMap['data']['uid'].toString());
      saveString(GROUP_ID, userMap['data']['group_id'].toString());
      getUserInfo(userMap['data']['token']);
    } else {
      Toast.toast(context, msg: msg);
      Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        return new BindWxPage(
          type: "wx",
          openId: resp.openid,
          nickname: resp.nickname,
          avatar: resp.headimgurl,
          sex: resp.sex.toString(),
        );
      }));
    }
  }

  getUserInfo(String token) async {
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetUserMsgUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
       Toast.toast(context, msg: "登录成功:"+userMap['data']['user_msg']['phone']);
       empower(userMap['data']['user_msg']['phone']);
       print(userMap['data']['user_msg']['phone']);
        APPLIC.userInfoMap = userMap['data'];
        _saveLogin(userMap['data']['user_msg']['phone']);
    }
  }
  void _saveLogin(String phone) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString("name", phone);
    APPLIC.eventBus.fire(UserInfoEvent(APPLIC.userInfoMap));
    APPLIC.eventBus.fire(LoginEvent());
    Navigator.of(context).pop();
  }
  void focusNodeChange() {
    barModel.focusNodeListener();
    setState(() {});
  }

  empower(String phone) async {
    Map map = new Map();
    map['phone'] =phone;
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.kGetEmpowerURL, data: data);
    Map userMap = json.decode(response.data);
  }

  @override
  void dispose() {
    barModel.removeFocusListeners();
    super.dispose();
    eventBus.fire(new RefreshData('登录成功'));
  }

  requestLogin() async {
    if (_userNameController.text == '' || _userPwdController.text == '') {
      Toast.toast(context, msg: '填写完整登录信息');
      return;
    }
    FormData data = new FormData.fromMap(
        {"account": _userNameController.text, "pwd": _userPwdController.text});
    Response<String> response = await HttpUtil().post(Api.LoginUrl, data: data);
    Map userMap = json.decode(response.data);
    Map userMsg = userMap;
    int code = userMap['code'];
    if (code == 1) {
       empower(_userNameController.text);
      APPLIC.eventBus.fire(LoginEvent());
      _saveLoginMsg();
      _saveUserMsg(userMsg['token'], userMsg['uid'], userMsg['group_id']);
      Navigator.pop(context, '');
    } else {
      Toast.toast(context, msg: userMap['msg']);
    }
  }
}
